#pragma once
#include<iostream>
#include<unistd.h>
#include<cstring> 
#include <sys/types.h>  
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
      

const int backlog=10;
Log lg;
enum {
errsocket=1,
errbind,
errlisten,
erraccept,
};
class Sock
{
public:
    Sock()
    {
    }
    void Socket()
    {
        listensockfd_=socket(AF_INET,SOCK_STREAM,0);
        if(listensockfd_<0)
        {
            lg(Fatal,"listensockfd error...,listensockfd_ is:%d",listensockfd_);
            exit(errsocket);
        }
        lg(Info ,"listensockfd success...,listensockfd_ is:%d",listensockfd_);
    }
    void Bind(const uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_port=htons(port);
        local.sin_family=AF_INET;
        local.sin_addr.s_addr=INADDR_ANY;//Address to accept any incoming messages.
       int n= bind(listensockfd_,(sockaddr*)&local,sizeof(local));
       if(n<0)
       {
         lg(Fatal,"bind error...");
         exit(errbind);
       }
       lg(Info,"bind success...");

    }
    void Listen()
    {
        int n=listen(listensockfd_,backlog);
        if(n<0)
       {
         lg(Fatal,"Listen error...");
         exit(errlisten);
       }
       lg(Info,"listen success...");
    }
    int Accept(std::string* clientip,uint16_t* clientport)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        memset(&client,0,sizeof(client));
        int sockfd=accept(listensockfd_,(sockaddr*)&client,&len);
        if(sockfd<0)
        {
            lg(Fatal,"accept error...");
            exit(erraccept);
        }
        lg(Info,"accept success...");
        *clientport=ntohs(client.sin_port);
        char ipstr[64];
        inet_ntop(AF_INET,&client.sin_addr,ipstr,sizeof(ipstr));
        *clientip=ipstr;
        return sockfd;
    }
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&peer.sin_addr);
         int n = connect(listensockfd_, (struct sockaddr*)&peer, sizeof(peer));
        if(n == -1) 
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }
     void Close()
    {
        close(listensockfd_);
    }
    int Fd()
    {
        return listensockfd_;
    }
    

private:
    int listensockfd_;
};
